import { reactive, ref } from "vue";
import { getSysApiList, type SysApi } from "@/views/domain/admin/api/sysApi";

export type SysApiTree = SysApi & { children?: SysApiTree[] };

export function useSysApi() {
  const query = reactive({
    title: "",
    pageNum: 1,
    pageSize: 10000
  });

  const apiList = ref<SysApi[]>([]);
  const apiTree = ref<SysApiTree[]>([]);

  const reloadApiList = async (buildTree: boolean = false) => {
    const { data } = await getSysApiList(query as any);
    apiList.value = data.list;
    if (buildTree) {
      buildApiTree(data.list);
    }
  };

  const buildApiTree = (list: SysApi[]) => {
    const apiGroupMap: Record<string, SysApiTree> = {};
    list.forEach(api => {
      apiGroupMap[api.group] = {
        ...api,
        path: api.group,
        title: api.group,
        children: []
      };

      for (const key in apiGroupMap) {
        apiGroupMap[key].children = list.filter(
          item => item.group === key
        ) as SysApiTree[];
      }

      apiTree.value = Object.values(apiGroupMap);
    });
  };

  return {
    query,
    apiList,
    apiTree,
    buildApiTree,
    reloadApiList
  };
}
